import React, { CSSProperties, FC, useEffect, useState } from 'react'
interface Item {
  color: string
  market: any
  origin: any,
  title: string,
  value: string,
  width: number,
  x: number,
  y: number
}
interface Props {
  pId: string,
  containerStyle?: React.CSSProperties,
  currentItem: {
    x: number
    y: number
    tooltip: any
    items: Item[]
  }
}
const PREFIX = 'gzwTooltip'
const getClassName = (str = '') => `${PREFIX}${str}`
const Tooltip: FC<Props> = ({ currentItem, pId, children, containerStyle }) => {
  let ref: any
  const [style, setStyle] = useState<CSSProperties>({})
  const getPosition = () => {
    const container = document.getElementById(pId)
    const parent = container?.getBoundingClientRect()
    const rect = ref?.getBoundingClientRect()
    if (parent && rect && currentItem) {
      const { x, items } = currentItem
      const maxY = Math.max(...items.map(v => v.y))
      let left = x - (rect.width / 2)
      let top = (maxY - rect.height - 30)
      if ((left + rect.width) > parent.width) {
        left = parent.width - rect.width - 25
      }
      if (x < rect.width / 2) {
        left = 30
      }
      return {
        left,
        top
      }
    }
    return {
      left: 0,
      top: 0
    }
  }
  const clickEvent = (e: any) => {
    const path = e.path
    let p = document.getElementById(pId)
    if (!((path?.length > 0 && path[0] === p) || (path?.length > 1 && path[1] === p))) {
      setStyle({ opacity: 0 })
    }
  }
  useEffect(() => {
    if (pId && currentItem) {
      setStyle({ ...getPosition(), opacity: '1', ...containerStyle })
    }
  }, [pId, currentItem, containerStyle])

  useEffect(() => {
    document.body.addEventListener('click', clickEvent)
    return () => {
      document.body.removeEventListener('click', clickEvent)
    }
  }, [])
  // 获取
  return (
    <div style={style} className={getClassName()} ref={(r) => {
      ref = r
    }}>
      <div className={getClassName('Arrow')}></div>
      {children}
    </div>
  )
}
export default Tooltip
